//var token = "";
var selNode = '';

function rpcCall(url, data, success) {
    return $.ajax({
        url:url ,
        dataType:'json',
        data:data,
        type:'POST',
        success:success,
        error:function(data)
        {
            alert(data);
        }
    });
}

function kpdir(token, fileId){
    rpcCall('kuaipan/dir/', "token=" + token + "&fileId=" + fileId,
        function (data){
            alert(data);
        }
    );
}

function init_tree(token){
//$.ajaxSetup({cache:false});//ajax调用不使用缓存    
    $("#fileTree").jstree({
        "plugins" : ["themes", "ui","json_data", "types", ],	
		"json_data": {
			"ajax" : {
				"url" : "kuaipan/dir/",
				"data" : function (n) {      
					return { id : n.attr ? n.attr("id") : 'root', token:token}; 
				}
			}
		},
		"types" : {
				// I set both options to -2, as I do not need depth and children count checking
				// Those two checks may slow jstree a lot, so use only when needed
				"max_depth" : -2,
				"max_children" : -2,
				// I want only `drive` nodes to be root nodes 
				// This will prevent moving or creating any other type as a root node
				"valid_children" : [ "root" ],
				"types" : {
					// The default type
					"default" : {
						// I want this type to have no children (so only leaf nodes)
						// In my case - those are files
						"valid_children" : "none",
						// If we specify an icon for the default type it WILL OVERRIDE the theme icons
						"icon" : {
							"image" : "/static/img/file.png"
						}
					},
					// The `folder` type
					"folder" : {
						// can have files and other folders inside of it, but NOT `drive` nodes
						"valid_children" : [ "default", "folder" ],
						"icon" : {
							"image" : "/static/img/folder.png"
						}
					},
					// The `drive` nodes 
					"root" : {
						// can have files and folders inside, but NOT other `drive` nodes
						"valid_children" : [ "default", "folder" ],
						"icon" : {
							"image" : "/static/img/root.png"
						},
						// those options prevent the functions with the same name to be used on the `drive` type nodes
						// internally the `before` event is used
						"start_drag" : false,
						"move_node" : false,
						"delete_node" : false,
						"remove" : false
					}
				}
			}
	  	}
    ).bind("select_node.jstree", function (e, data){
        selNode = data.rslt.obj;
    }); // end tree
}
function download(fileId, token){
    rpcCall("/kuaipan/down/", "token=" + token + "&fileId=" + fileId, function (data){
        alert(data);
    });
}
function fileTree(token) {
    $("#dialogChoseFile").dialog({
        modal: true,
        buttons:{
            '打开选中文件': function() {
                if(selNode && selNode.attr("rel") != "file")
                {   
                    alert("not a file.");
                    return;
                }
                selNode.attr("id");
                $("#dialogChoseFile").dialog('close');
            },
            取消: function() {
                $("#dialogChoseFile").dialog('close');
            },
        },
        open:function (event, ui) {            
        	init_tree(token);
        }   
    })// end dialog
}



function _init() {
    var token = '';
    $("#dialogLogin").dialog("destroy");
     var email = $("#email"),
        psw = $("#passwd"),
        tips = $(".validateTips");
        
    function updateTips(t) {
        tips.text(t)
            .addClass('ui-state-highlight');
        setTimeout(function() {
            tips.removeClass('ui-state-highlight', 1500);
        }, 500);
    }
    
    function chkEmail(){
        return(email.val().length > 6 && email.val().length < 128 &&
        email.val().indexOf('@') > 2);
    }
    function chkPassword(){
        return(psw.val().length >= 6 && psw.val().length < 40);
    }
    $("#dialogLogin").dialog({
        modal: true,
        buttons: {
            登录: function() {
                
                if (chkEmail()){
                    email.removeClass('ui-state-error');
                    updateTips('email OK.');
                }else{
                    email.addClass('ui-state-error');
                    return updateTips('没效的email地址。')
                }
                if (chkPassword()) {
                    psw.removeClass('ui-state-error');
                    updateTips('password OK.');
                }else{
                    psw.addClass('ui-state-error');
                    return updateTips('password format error.');
                }
                
                $.ajax({
                    url:'kuaipan/login/' ,
                    dataType:'json',
                    data:'email=' + email.val() + '&password=' + psw.val(),
                    type:'POST',
                    success:function(data)
                    {
                        if (data.result != 'ok'){
                            return updateTips(data.result);
                        }
                        $("#dialogLogin").dialog("close"); 
                        fileTree(data.xLive.token);
                        $("#dialogChoseFile").dialog("open");
                    },
                    error:function(data)
                    {
                        alert(data);
                    }
                })
            },
            取消: function() {
                $(this).dialog('close');
            },
        }
    });
    $('#showDialog').button().click(function() {
        $('#dialogLogin').dialog('open');
    });
}

$(document).ready(function(){
    //_init();
   $("#dialogChoseFile").dialog("open");
   fileTree('dd');
   
});
